import 'package:ceramics/extensions/ab_widget_extensions.dart';
import 'package:ceramics/model/ab_works.dart';
import 'package:ceramics/pages/main/home/ab_home_detail_page.dart';
import 'package:ceramics/pages/main/home/welcome_dialog.dart';
import 'package:ceramics/styles/ab_styles.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:shared_preferences/shared_preferences.dart';

import 'ab_home_works_item.dart';

class ABHomeController extends GetxController {
  var works = <ABWorks>[].obs;

  @override
  onInit() {
    super.onInit();
    loadData();
    _showWelcomeDialog();
  }

  Future<void> loadData() async {
    works.value = await ABWorks.homeWorks();
  }

  _showWelcomeDialog() async {
    var sp = await SharedPreferences.getInstance();
    var firstOpen = sp.getBool('firstOpenHome') ?? true;
    if (!firstOpen) {
      return;
    }
    Future.delayed(const Duration(seconds: 1), () {
      Get.dialog(const WelcomeDialog());
    });
  }
}

class ABHomePage extends GetView<ABHomeController> {
  const ABHomePage({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      extendBodyBehindAppBar: true,
      appBar: AppBar(title: const Text("CERAMICS WORKS LIST", style: TextStyle(
          fontFamily: "RacingSansOne", color: ABStyles.orange)),
          backgroundColor: Colors.white.withOpacity(0.1)),
      body: Obx(() {
        return Container(
          decoration: const BoxDecoration(
              image: DecorationImage(
                image: AssetImage("images/login_bg.webp"),
                fit: BoxFit.fill,
              ),
              color: Colors.green
          ),
          child: SafeArea(
            bottom: false,
            child: ListView.separated(
                padding: const EdgeInsets.only(left: 10,
                    right: 10,
                    bottom: kBottomNavigationBarHeight + 80),
                itemBuilder: (ctx, idx) {
                  var works = controller.works[idx];
                  return ABHomeWorksItem(
                      works: works, idx: idx).onTap((){
                    Get.to(()=>ABHomeDetailPage(id: works.id.toString()),arguments: works);
                  });
                },
                separatorBuilder: (ctx, idx) {
                  return const Divider();
                },
                itemCount: controller.works.length),
          ),
        );
      }),
    );
  }
}
